import React, { useState, useEffect } from 'react';
import { Form, Input, Button, message, Upload, Avatar } from 'antd';
import { UploadOutlined, UserOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { register } from '../api/user';
import { useUserStore } from '../store/user';
import 'antd/dist/reset.css';

const Register: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [avatarUrl, setAvatarUrl] = useState<string | undefined>(undefined);
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const { token } = useUserStore();

  // 检查登录状态
  useEffect(() => {
    if (token) {
      navigate('/home');
    }
  }, [token, navigate]);

  const beforeUpload = (file: File) => {
    setAvatarFile(file);
    // 预览
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => setAvatarUrl(reader.result as string);
    return false; // 阻止自动上传
  };

  const onFinish = async (values: any) => {
    if (!avatarFile) {
      message.error('请先上传头像');
      return;
    }
    setLoading(true);
    try {
      const formData = new FormData();
      formData.append('username', values.username);
      formData.append('password', values.password);
      formData.append('nickname', values.nickname);
      formData.append('file', avatarFile);
      const res = await register(formData);
      console.log('注册返回结果', res.data);
      if (res.data.success) {
        message.success(res.data.message || '注册成功！请登录');
        setTimeout(() => {
          navigate('/login');
        }, 1000);
      } else {
        message.error(res.data.message || '注册失败');
        form.setFieldsValue(values);
      }
    } catch (error) {
      message.error('网络错误，请稍后重试');
      form.setFieldsValue(values);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Form 
      form={form}
      onFinish={onFinish} 
      style={{ maxWidth: 300, margin: '0 auto', marginTop: 100 }}
    >
      <Form.Item style={{ textAlign: 'center' }}>
        <Avatar size={64} src={avatarUrl} icon={<UserOutlined />} />
      </Form.Item>
      <Form.Item label="上传头像" style={{ marginBottom: 0 }}>
        <Upload
          showUploadList={false}
          beforeUpload={beforeUpload}
          accept="image/*"
        >
          <Button icon={<UploadOutlined />}>选择图片</Button>
        </Upload>
      </Form.Item>
      <Form.Item 
        name="nickname" 
        rules={[
          { required: true, message: '请输入昵称' },
          { min: 2, message: '昵称至少2个字符' },
          { max: 20, message: '昵称最多20个字符' }
        ]}
      > 
        <Input placeholder="昵称" />
      </Form.Item>
      <Form.Item 
        name="username" 
        rules={[
          { required: true, message: '请输入用户名' },
          { min: 2, message: '用户名至少2个字符' },
          { max: 20, message: '用户名最多20个字符' }
        ]}
      > 
        <Input placeholder="用户名" />
      </Form.Item>
      <Form.Item 
        name="password" 
        rules={[
          { required: true, message: '请输入密码' },
          { min: 6, message: '密码至少6个字符' },
          { max: 20, message: '密码最多20个字符' }
        ]}
      > 
        <Input.Password placeholder="密码" />
      </Form.Item>
      <Form.Item 
        name="confirm" 
        dependencies={['password']}
        rules={[
          { required: true, message: '请确认密码' },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('两次输入的密码不一致！'));
            },
          }),
        ]}
      > 
        <Input.Password placeholder="确认密码" />
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit" loading={loading} block>注册</Button>
      </Form.Item>
      <Form.Item>
        <Button type="link" block onClick={() => navigate('/login')}>已有账号？去登录</Button>
      </Form.Item>
    </Form>
  );
};

export default Register; 